import os
import sys
import subprocess
import time
import threading
from pathlib import Path

def get_venv_python():
    """获取虚拟环境中的Python解释器路径"""
    if sys.platform == "win32":
        return str(Path(".venv/Scripts/python.exe").resolve())
    else:
        return str(Path(".venv/bin/python").resolve())

def print_output(pipe, prefix=""):
    """打印子进程的输出"""
    try:
        for line in iter(pipe.readline, ''):
            if line.strip():
                print(f"{prefix}{line.strip()}")
    except UnicodeDecodeError as e:
        print(f"{prefix}UnicodeDecodeError: {str(e)}")

def main():
    # 获取当前工作目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 切换到项目根目录
    os.chdir(current_dir)
    
    # 获取虚拟环境中的Python解释器
    python_path = get_venv_python()
    
    # 检查虚拟环境是否存在
    if not os.path.exists(python_path):
        print("错误：虚拟环境不存在，请先创建虚拟环境")
        print("运行命令：python -m venv .venv")
        sys.exit(1)
    
    # 启动FastAPI服务器
    print("正在启动服务器...")
    try:
        # 使用虚拟环境中的Python启动main.py
        process = subprocess.Popen(
            [python_path, "main.py"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True,
            bufsize=1,
            env={**os.environ, "PYTHONUNBUFFERED": "1"}
        )
        
        # 创建线程来打印输出
        stdout_thread = threading.Thread(target=print_output, args=(process.stdout, "[INFO] "))
        stderr_thread = threading.Thread(target=print_output, args=(process.stderr, "[ERROR] "))
        stdout_thread.daemon = True
        stderr_thread.daemon = True
        stdout_thread.start()
        stderr_thread.start()
        
        # 等待服务器启动
        time.sleep(2)
        
        if process.poll() is None:
            print("\n服务器已启动！")
            print("按 Ctrl+C 停止服务器")
            print("服务器运行在 http://localhost:8000")
            print("API文档地址: http://localhost:8000/docs")
        else:
            print("\n服务器启动失败！")
            sys.exit(1)
        
        # 保持进程运行
        while True:
            if process.poll() is not None:
                print("\n服务器意外停止！")
                break
            time.sleep(1)
            
    except KeyboardInterrupt:
        print("\n正在停止服务器...")
        process.terminate()
        process.wait()
        print("服务器已停止")
    except Exception as e:
        print(f"\n启动服务器时发生错误: {str(e)}")
        if 'process' in locals():
            process.terminate()
            process.wait()
        sys.exit(1)

if __name__ == "__main__":
    main() 